package com.base.starter.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.base.common.base.BaseUserEntity;
import com.base.common.constant.FillConstant;
import com.base.domain.moudles.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
* @Description: 实现MetaObjectHandler可以在插入或修改操作时，给一些字段设置默认值
* @Param:  
* @return:  
* @Author: zhou minghao
* @Date: 9:19 2024/4/17
*/ 
@Slf4j
@Component
public class CommonFieldFillingHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //调用当前时间作为createTime字段的值填充进去
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        //将常量作为status的字段的值填充进去
        this.strictInsertFill(metaObject, "status", String.class, FillConstant.STATUS_TYPE_ENABLE);
        //统一设置创建人，创建时间，创建人名等公共字段。
        Object principal = SecurityUtils.getSubject().getPrincipal();
        if(Objects.isNull(principal)){
            return;
        }
        //检查是不是BaseUserEntity的实例，如果是则将时间和创建用户id设置
        User user = (User) principal;
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof BaseUserEntity) {
            BaseUserEntity userEntity = (BaseUserEntity) metaObject.getOriginalObject();
            userEntity.setCreateTime(new Date());
            userEntity.setCreateUserId(user.getId());
            return;
        }
        //不是则将当前id设置到填充到相应的字段
        this.strictInsertFill(metaObject, "createUser", Integer.class, user.getId());
        this.strictInsertFill(metaObject, "createUserId", Integer.class, user.getId());
        this.strictInsertFill(metaObject, "addUserId", Integer.class, user.getId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object principal = SecurityUtils.getSubject().getPrincipal();
        if(Objects.isNull(principal)){
            return;
        }
        //统一设置修改人，修改时间，修改人名等公共字段。
        User user = (User) principal;
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof BaseUserEntity) {
            BaseUserEntity userEntity = (BaseUserEntity) metaObject.getOriginalObject();
            userEntity.setUpdateTime(new Date());
            userEntity.setUpdateUserId(user.getId());
            return;
        }
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "updateUserId", Integer.class, user.getId());
        this.strictUpdateFill(metaObject, "lastUpdateTime", Date.class, new Date());
    }
}
